Sunday, 21 August 2016

Creating a base view in backbone marianotte js the good way

Marionette JS is based on Backbone JS and a lot of the module extend from basic backbone modules. Here i learn when i extend a module whether it was a view or model or anything you will do like this :

var BaseForm = Marionette.ItemView.extend({

    

      initialize: function(){

           this.title = "title"

      },



});


and to use it on a custom page view base on the BaseForm you will do this :

var contactForm = BaseForm.extend({

    

      initialize: function(){

            this.rows = 2;

      },



});


Above problem is the main object title from the BaseForm is gone, except you do this inside contactForm :

       initialize: function(){

             BaseForm.prototype.initialize.call(this);

             this.rows = 2;

      },


With the above method, anything initialized on the BaseForm will still be available.

But this create problem that everytime you override the initialize, you need call the prototype. How if we not touch the initialize in the BaseForm, and just create a new method, that will be checked by the initialize method on the BaseForm.
So here are the new way on doing this :

//BaseForm default initialize

var BaseForm = Marionette.ItemView.extend({

    

      initialize: function(){

           this.title = "title",



          if (this.additionalInit){

              this.additionalInit();

          },



      },



});

//we extend from BaseForm without touch initialization code
var contactForm = BaseForm.extend({
   
      additionalInit: function(){
            this.rows = 2;
      },
});

The benefit of this, any developer want to use the module, no need break the module by override the initialization, or if do want additional custom function running after the initialization base modul load, provide the function that the initialization checks, in this case additionalInit function.


0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More