Is there a reason I should avoid this in Backbone.js?

I like backbone.js more and more. I want to have several views for this model:

  • A view list in which each model has a view with its own element li.
  • Detailed view showing all the details of the model.

My question is: I was looking for a good way to allow one species to communicate with another and chose the following:

/** Allow a model to keep track of it views. **/
Backbone.Model.prototype.addView = function (view) {
    // Ensure our model has a view array.
    if (typeof this.views === 'undefined')
    {
        this.views = [];
    }

    // Append our newest view to the array only if it is not already present.
    if (_.indexOf(this.views, view) === -1)
    {
        this.views.push(view);
    }
}

/** Allow a model to remove all of it views.
 * 
 * @param {Object} args Any arguments will be provided to the view method.
 */
Backbone.Model.prototype.unloadViews = function (args) {
    var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
    for (var i = 0; i < n; i++)
    {
        var view = this.views[i];
        if (typeof view.unloadView === 'function')
        {
           view.unloadView(args);
        }
    }
}

/** Allow a model to re-render all of it views.
 * 
 * @param {Object} args Any argyments will be provided to the view method.
 */
Backbone.Model.prototype.renderViews = function (args) {
   var n = (typeof this.views === 'undefined') ? 0 : this.views.length;
   for (var i = 0; i < n; i++)
   {
        var view = this.views[i];
        if (typeof view.render === 'function')
        {
            view.render(args);
        }
   }
}

My questions

  • Am I missing something when I study backbone.js, which will let me do this nativly?
  • Is there a reason I should avoid this?

Additional Information

( ) GitHub: https://github.com/aarongreenlee/Learning-backbone.js. , : https://github.com/aarongreenlee/Learning-backbone.js/commit/ea4e61d934d2f987726720e81c479f9d9bb86e09#diff-2 ( ).

!

+3
2

, , !

(re render that is).

, (, , ) , . MVC.

, addViews, removeViews Backbone.View, . , , sproutcore.

!

+13

Twitter

@aarongreenlee - , , . - @jashkenas

+1

Source: https://habr.com/ru/post/1779646/


All Articles