GithubHelp home page GithubHelp logo

backbone.advice's Introduction

Backbone.Advice

Use requireJS to import -- or whatever you want.

Based on the Advice functional mixin library by Angus Croll. Adds functional mixin abilities for Backbone objects.

There can be issues when extending classes that already have mixins and you may overrwrite needed functionality that has been mixed in. To get around this we use Backbone.AdviceFactory.

Features

Gives a convenient way to add functionality as needed and reuse components together.

Installation

Bower

To install Backbone.Advice via Bower:

bower install backbone.advice

From source

Download the latest zip file or clone the repository from GitHub:

git clone https://github.com/rhysbrettbowen/Backbone.Advice

Usage

Advice and Mixins are provided for use with requirejs, if you'd just like to add them in with script tags then just remove the define function call.

// add the mixin capability (may already be done for you)
Backbone.Advice.addMixin(Backbone.View)

// define a mixin
var namer = function(options) {
	// options an object that may be passed in

	// any functions under clobber will be replaced
	this.clobber({
		initialize: function() {
			this.spoke = options.times || 0;
		}
	});

	// these will only be set if there is no existing function
	this.setDefaults({
		name: 'frank',
		getName: function() {
			return this.name;
		},
		speak: function() {
			console.log('hello ' + this.getName());
		}
	});

	// first argument will be the original function - can also take an object of functions
	this.around('getName', function(orig) {
		return orig().split(' ')[0];
	});

	// can even extend objects - useful for adding events
	this.addToObj({
		events: {
			'greeted' :'speak'
		}
	});

	// first argument will be the original function - can also take an object of functions
	this.before('speak', function() {
		this.spoke++;
	});

	// first argument will be the original function - can also take an object of functions
	this.after('speak', function() {
		console.log('for the ' + this.spoke + 'th time');
	});

}


var Speaker = Backbone.View.extend({
	name: 'Bob White' // the set defaults won't override this
}).mixin([
	namer
], { // options passed in
	times: 3
});

var bob = new Speaker();
bob.speak();  // Hello Bob
              // for the 4th time

You can even call addToObj, clobber, setDefaults, after, before and around straight on the constructor rather than creating the mixin function:

var ShoutName = Speaker.extend().around('getName', function(orig) {
	return orig().toUpperCase();
});

We can also setup a sort of pseudo inheritance between mixins, say we wanted the previous example to work on it's own we could do this:

var shouter = function(options) {

	// pull in any other mixins this one depends on
	this.mixin([
		namer
	], options);

	// now we can decorate
	this.around('getName', function(orig) {
		return orig().toUpperCase();
	});
}

var ShoutName = Backbone.View.extend().mixin([
	shouter
]);

Mixins will keep a record of what has been put on, so a mixin will only be applied once (this may cause issues if you'd like to re-apply a mixin with a different set of options).

notice that we're extending before the mixin to get the right prototype chain before mixing in.

Mixins can also be objects like this:

var myMixin = {
	clobber: {
		clobbered: true;
	},
	addToObj: {
		events: {
			'click': 'onClick'
		}
	},
	after: {
		'render': function() {
			console.log('rendering done');
		}
	}
};

Be careful though, only mixins that were defined as functions are able to see if they have been applied before. To fix this you can return the object from a function:

var myMixinFn = function() {
	return myMixin;
}

or even use the return method to pass in the options object:

var myMixinFn = function(options) {
	return {
		setDefaults: {
			number: options.number
		}
	};
}

see Backbone.Advice.Mixins (mixin.js) for some useful mixins you can use today!

Tests

Install dependencies

bundle install

and open the file test.html in your browser.

TBD: re-enable testing with testacular/karma.

#Changelog

##Advice

###v1.0.0

  • initial versioning

##Mixin

###v1.0.0

  • initial versioning

backbone.advice's People

Contributors

disruptek avatar marcpare avatar rhysbrettbowen avatar stah avatar thirtified avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

backbone.advice's Issues

Monkey patch Backbone.extend for better syntactic sugar?

I really like the way Cocktail patches the extend method so that mixin includes can be written far more clearly (imho) in the form;

var MyView = Backbone.View.extend({
  mixins: [MyMixin1, MyMixin2],

  etc...
});

Any chance of similar in Advice?

Possible 'strict' violations

We are using JSHint and modules with Advice. It all works pretty well; however, JSHint will complain about "possible strict violations." This is basically just hurting my feelings ha.

Have you found a good solution to get around all the linting warnings?

Allow addToObj to accept a function that return an object

First, great project!

It should be interesting if we could pass to addToObj names of prototype functions that return an object, and do the extend with this value, so we could declare for example events as a function(which return an object) as it is usual in backbone for easy inheritance method overloading.

wrong return-value when mixing in a previously-unknown method name

  myMixin = function() {
    return { foo: function() { return "My foo result" }
  }
  myOtherClass = function() {}.mixin(myMixin); // mumble - point is, it doesn't have 'foo'.
  myOtherClass.foo("some arg");  // returns "some arg"

I expected this to return "My foo result".

Currently, I have to specify 'clobber' for a function name that didn't exist before, because the identity function's return value is returned instead of my function's return value. Surprise! and :(

I'd sort of hope that after would recognize the no-original-method case, and take a shortcut whereby we just create the method with direct reference to the new method. Methods aside, the outcome still seems wrong.

Mixed-in functions can't return values

I'm running into a problem in which I'm mixing two methods into a view, one of which needs a value returned by the other. The problem is, the second method always returns undefined. You can test this pretty easily by running this code in your console:

Backbone.View.mixin({
    callee : function () {
        return "some value";
    },
    caller : function () {
        console.log(this.callee());
    }
});

new Backbone.View().caller(); // undefined

I'm trying to investigate the cause further; I'll update this issue when and if I figure out more.

Tests don't run with latest version of Karma, tests fail on old version of Karma

I just installed Karma to try to get the tests to run and it seems that Karma has changed their config file format, and the tests won't run out of the box.

Steps to reproduce:

sudo npm install -g karma
karma start

I get this error:

ERROR [config]: Config file must export a function!
  module.exports = function(config) {
    config.set({
      // your config
    });
  };

I also did some investigation and tried version 0.8.4 of Karma (the version available around the time the last commit to karma.conf.js was made), and I ran into a problem actually running the test.

Steps to reproduce:

sudo npm install -g phantomjs
sudo npm install -g [email protected]
karma start

I get this error:

PhantomJS 1.9 (Linux) Backbone.Advice should be able to override mixin options should not override only on tha applied constructor FAILED
    expected 2 to equal 3

I don't know if this relates to using the latest version of PhantomJS or not. I have not tried a previous version of PhantomJS to coincide with 0.8.4 of Karma.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.