backbone.js accessing model attributes within model - this.attribute VS this.get('attribute')?

前端 未结 2 2031
别跟我提以往
别跟我提以往 2021-02-13 00:57

From my understanding the attributes of a Backbone.js model are supposed to be declared as somewhat private member variables by saying

this.set({ attributeName:          


        
2条回答
  •  無奈伤痛
    2021-02-13 01:44

    Never is an incomplete answer.

    Sometimes you want access to the collection of model attributes - whatever those attributes might be. Consider a utility method to perform calcs on attributes, format them for output, etc.

    A convenient way to do this is to access model.attributes

    Consider one alternative, below:

    var attributesNames = ['foo', 'bar', 'baz'];
    var attributes = _(attributesNames ).map(function(attr) { return model.get(attr); });
    
    callSomeUtilityMethod(attributes);
    

    Two problems:

    • We've introduced coupling in the "attributeNames" collection. What if that list changes?
    • We've lost the association of name/value. We could rewrite the map above, but it becomes more work.

    In this scenario, it's much more convenient to do something like this:

    callSomeUtilityMethod(model.attributes);
    

提交回复
热议问题