-
Notifications
You must be signed in to change notification settings - Fork 13
Work with popular JS Lib
James Yang edited this page Mar 19, 2018
·
19 revisions
cssobj is good for using with vanilla JS or any JS libs like MVC frameworks
Think below code at head of your page:
var obj = {
'.nav': {
'.item': {
color: 'blue',
'&.active': {
color: 'red'
}
}
}
}Just like your normally use with plain css, just beware of local class names
You may want to use with:
You can use react-cssobj with React
// get result from cssobj
var result = cssobj(obj, {local: true})
// get local selector
$(result.mapSel('.nav .item')).append(...)
// get local class list
$('div').addClass(result.mapClass('!news item active'))For mithril, please check out cssobj-mithril, for zero effect to mapClass
Without above repo, you can just use mithril natively as below:
fiddle demo Please open console and see local class names work!
var component = {
controller: function () {
var self = this
this.result = cssobj(obj, {local:true})
this.updateCSS = () => {
obj['.nav'].fontSize = '34px'
self.result.update()
}
},
view: function (ctrl) {
var result = ctrl.result
return m (
result.mapSel('ul.nav'),
m (
result.mapSel('li.item'),
{
class: result.mapClass('!news item active'),
onclick: ctrl.updateCSS
},
'cssobj is awesome!'
)
)
}
}
m.mount(document.getElementById('container'), component)Notice, if you use Vue2.0, should check babel-plugin-transform-cssobj to simplify mapClass
cssobj can use in Vue component for better capsulation.
fiddle demo Please open console and see local class names work!
HTML
<template id="my-template">
<ul class="{{'nav' | mapClass}}" @click="updateCSS">
<li class="{{'!news item active' | mapClass}}">cssobj is awesome!</li>
</ul>
</template>
<div id="app">
<my-component></my-component>
</div>JS
// register a custom filter
Vue.filter('mapClass', function (value) {
return this.result.mapClass(value)
})
// you component here
Vue.component('my-component', {
template: '#my-template',
data: function () {
return {
result: cssobj(obj, {local: true})
}
},
methods: {
updateCSS: function () {
obj['.nav'].fontSize = '34px'
this.result.update()
}
}
})
new Vue({
el: '#app'
})Angular has more power to work with cssobj.
HTML
<div ng-app>
<div ng-controller="CssobjCtrl">
<ul ng-class="mapClass('nav')" ng-click="updateCSS()">
<li ng-class="mapClass('!news item active')">[+ click me +] cssobj is awesome!</li>
</ul>
</div>
</div>JS
function CssobjCtrl($scope) {
var result = cssobj(obj, {
local: true
})
$scope.updateCSS = function() {
obj['.nav'].fontSize = '34px'
result.update()
}
$scope.mapClass = function(list) {
return result.mapClass(list)
}
}Contribution welcome :)