简体   繁体   中英

How to toggle backbone.js's model attributes?

In my js code I noticed many statements like:

model.set({someAttribute : !model.get("someAttribute")});

So I thought it may be useful to define custom method in the model:

toggle: function(attr, silent){
    this.set({attr: !this.get(attr)}, silent? {silent:true} : {});
}

The problem is, javascript javascript treats 'attr' as an actual key name instead of formal function parameter, so the code above doesn't work. Any suggestions how to solve this problem? I want an elegant one-line solution.

there isn't an elegant one-line solution for this. in order to use attr as the key, you have to declare the object literal and then set it using the [] syntax:

toggle: function(attr, silent){
  var data = {}, value = this.get(attr);
  data[attr] = !value;
  this.set(data, {silent: silent});
}

Well, you had (edit) all sorts of syntax errors with the "silent" portion of your function and I'm not sure what it is for, so I will focus on your question at hand. This is the most elegant solution you are going to find, I think... "elegant" is subjective, of course.

Anyways, there is no way to have variable key names in the parameter initialization, so you need to use the index operator on a temporary object.

Here is how I solved it:

toggle: function(attr, silent) {
    var setter = {};
    setter[attr] = !this.get(attr);
    this.set(setter, silent? {silent: true} : {});
}
toggle: function( attr, s ){
    this.set(
        function( aname, aval ){
            var o = {};
            o[aname] = !aval;
            return o;
        }( attr, this[attr] ),
        s? {silent:true}:{}
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM