Skip to content

Instantly share code, notes, and snippets.

@bshack
Last active March 24, 2016 19:32
Show Gist options
  • Save bshack/839c00ed7ecc65847c15 to your computer and use it in GitHub Desktop.
Save bshack/839c00ed7ecc65847c15 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';
const _ = require('underscore');
module.exports = function(options) {
//cache this
let self = this;
//initialize
self.init = function() {
self.addListeners();
window.console.log('init', self);
};
self.el = document.createElement('div');
//empty model
self.model = {
};
//set up events
self.addListeners = function() {
self.el.addEventListener('click', self.eventClick);
};
//click event
self.eventClick = function(e) {
window.console.log(e, self);
e.preventDefault();
};
//render the view
self.render = function() {};
//extendable view
self = _.extend(self, options);
// init on instantiation
self.init();
// now run render on instantiation
self.render();
};
})();
@bshack
Copy link
Author

bshack commented Mar 24, 2016

viewBase.js would likely become the base that other views are extended from before being used in usage.js.

Backbone does it like this:

Backbone.View.extend({.....

@gibbitz
Copy link

gibbitz commented Mar 24, 2016

I see similarities to BB here. Are you looking to set a base for use with it or in lieu of it? (sorry I haven't used BB in more than a year and I'm like really old)

I see the use of variables on self's instance that could probably be prototypal (faster). Though going balls-in prototypal would inspire more modifications here (making this into a factory, not a constructor) and would be less compatible with BB (if that was the direction you were going).

@bshack
Copy link
Author

bshack commented Mar 24, 2016

not looking for any compatiblity, I would see this as a replacement on projects that would not want to use frameworks. Projects where you'd want to use a collection of libraries or leverage native js. Feel free to modify :)

@gibbitz
Copy link

gibbitz commented Mar 24, 2016

I had to make a fork (couldn't edit). You can follow the link at the top or just go here: https://gist.github.com/gibbitz/8e3d0ad18370f6e1f578

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