backbone-computed-properties
Version:
Ember style computed properties for Backbone.js Models
1 lines • 1.52 kB
JavaScript
!function(e,t){if("function"==typeof define&&define.amd)define(["backbone","underscore"],t);else{if("undefined"!=typeof exports)return module.exports=t(require("backbone"),require("underscore"));t(e.Backbone,e._)}}(this,function(e,t){function n(){var n,o=t.extend({},Object.getPrototypeOf(this),this.constructor.__super__);for(var i in o)o.hasOwnProperty(i)&&(n=o[i],n instanceof e.computed&&r(this,n,i))}e.Computed=e.computed=function(t){return this instanceof e.computed?(t=Array.prototype.slice.call(t,0),this.computedFunction=t[t.length-1],this.dep=t.slice(0,-1),void 0):new e.computed(arguments)},e.computed.prototype.getDependentProperties=function(){return this.dep};var o=e.Model;e.Model=o.extend({constructor:function(){o.apply(this,arguments),n.call(this)}});var r=function(e,n,o){var r=function(){e.set(o,n.computedFunction.call(e))},i=t.memoize(function(){return t.filter(n.getDependentProperties(),function(e){return e.indexOf("event:")<0})}),u=t.memoize(function(){return t.chain(n.getDependentProperties()).filter(function(e){return 0===e.indexOf("event:")}).map(function(e){return e.replace("event:","")}).value()}),c=function(){return i().map(function(e){return"change:"+e})},f=function(){if(i().length){var t=c().join(" ");e.on(t,r)}},p=function(){if(u().length){var t=u().join(" ");e.on(t,r)}};f(),p(),r()};return e.computed.alias=function(t){return e.computed(t,function(){return this.get(t)})},e.computed.equal=function(t,n){return e.computed(t,function(){return this.get(t)===n})},e.computed});