Skip to content

Instantly share code, notes, and snippets.

@gibbitz
Forked from bshack/usage.js
Last active March 24, 2016 23:25
Show Gist options
  • Save gibbitz/8e3d0ad18370f6e1f578 to your computer and use it in GitHub Desktop.
Save gibbitz/8e3d0ad18370f6e1f578 to your computer and use it in GitHub Desktop.
simple js view for being extended
(function() {
'use strict';
const View = require('./viewBase.js');
new View({
el: document.querySelector('a'),
model: {'foo': 'bar'}
});
})();
(function() {
'use strict';
module.exports = function(_options) {
// default property values
// provides a template object for _options overrides
var defaults = {
init : function(){
this.addListeners();
window.console.log('init', this);
},
el : document.createElement('div'),
model : {},
addListeners: function(){
this.el.addEventListener('click', self.eventClick);
},
eventClick : function(_e){
window.console.log(_e, this);
_e.preventDefault();
},
render: function(){
}
};
// return a "class" instance
return new function ViewBase(_opts){
Object.assign(this.constructor.prototype, defaults, _opts);
this.constructor.prototype.init.call(this);
this.constructor.prototype.render.call(this);
}(_options);
};
})();
@gibbitz
Copy link
Author

gibbitz commented Mar 24, 2016

Removed the underscore dependency (since you're all ES6 up in this b*tch)
Added a prototypical return object. Though I don't think you're gaining much there. The legibility goes down a notch and the usage stays the same.

While digging about in this I started thinking about the signatures and expected behaviors and They're "secret-handshakey". They only feel okay because of our familiarity with Backbone. There's a lot of opportunity to make init calls dynamic or pass in UI interaction event listeners as options etc. That sticking too closely to an existing framework takes away from. For instance. returning the the pseudo class directly would allow a more vanilla :

var selectorView = new ViewBase({
    el:'.selector-class', 
    events:{
      'mouseOver' : function(_event){
         // handle code here
      }
    }
});

or

var selectorView = new ViewBase();
selectorView.el = '.selector-class'; // this would require a setter, but -- hey es6!
selectorView.events.mouseOver = function(_event){
   // handle code here
};

Just some cents. Prolly not all 2 and likely without sense...

@bshack
Copy link

bshack commented Mar 24, 2016

i like this style the best:

var selectorView = new ViewBase({
el:'.selector-class',
events:{
'mouseOver' : function(_event){
// handle code here
}
}
});

How could we support events on child elements? Backbone does this:

events: {
'click header button': 'eventMenuToggle',
'click #accessible-ajax-example-button': 'eventAccessibleAjax'
},

This looks pretty good, think I will roll with this for my views when i don't want to do something third party.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment