Forked from wulftone/backbone-rivets.config.js
Last active
December 18, 2015 04:49
-
-
Save wkrsz/5728584 to your computer and use it in GitHub Desktop.
Some funky syntax for Rivets: model.@Attribute, model.attribute, model.computed().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Bind to backbone attribute (read/write with get/set, subscribe to change:attribute event): | |
// data-text="model.@attribute" | |
// | |
// Bind to output of function (calls the function to get value, subscribes to 'change' event): | |
// data-text="model.computedProperty() | |
// | |
// Bind to attribute (subscribes to 'change' event): | |
// data-text="model.attr" | |
(function(rivets){ | |
rivets.formatters.not = function(value){ | |
return !value; | |
}; | |
rivets.formatters.equals = function(value, other){ | |
return value == other; | |
}; | |
rivets.formatters.read = function(obj, key){ | |
if (obj) { | |
return obj[key]; | |
} | |
}; | |
var matchAttribute = function(keypath) { | |
var match = keypath.match(/^@(.+)/); | |
if (match) { | |
return match[1]; | |
} | |
}; | |
var matchFunction = function(keypath) { | |
var match = keypath.match(/^(.+)\(\)$/); | |
if (match) { | |
return match[1]; | |
} | |
}; | |
rivets.configure({ | |
adapter: { | |
subscribe: function(obj, keypath, callback) { | |
var name; | |
if (name = matchAttribute(keypath)) { | |
obj.on('change:' + name, callback); | |
} else if (obj instanceof Backbone.Model) { | |
obj.on('change validated', callback); | |
} else if (obj instanceof Backbone.Collection) { | |
obj.on('add remove reset', callback); | |
} | |
}, | |
unsubscribe: function(obj, keypath, callback) { | |
var name; | |
if (name = matchAttribute(keypath)) { | |
obj.off('change:' + name, callback); | |
} else if (obj instanceof Backbone.Model) { | |
obj.off('change', callback); | |
} else if (obj instanceof Backbone.Collection) { | |
obj.off('add remove reset', callback); | |
} | |
}, | |
read: function(obj, keypath) { | |
var name; | |
if (name = matchAttribute(keypath)) { | |
return obj.get(name); | |
} else if (name = matchFunction(keypath)) { | |
return obj[name].apply(obj); | |
} else { | |
var cur = obj, tok, tokens = keypath.split('.'); | |
while (cur && (tok = tokens.shift())) { | |
cur = cur[tok]; | |
} | |
return cur; | |
} | |
}, | |
publish: function(obj, keypath, value) { | |
if (name = matchAttribute(keypath)) { | |
obj.set(name, value); | |
} else { | |
obj[keypath] = value; | |
} | |
} | |
} | |
}); | |
})(rivets); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment