Last active
August 29, 2015 14:02
-
-
Save erran-r7/58bde295d0b2137d1f2d to your computer and use it in GitHub Desktop.
An example of how backbone extends object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Javascript function as an object (class) | |
var Person = { | |
sayHello: function (otherPerson) { | |
console.log("Hello, "+otherPerson.name+"!"); | |
}, | |
name: 'Anon', | |
new: function (name) { | |
this.name = name; | |
return this; | |
} | |
} | |
// You'd use Person.new(name) to create a person vs. `new Person(name)` | |
john = Person.new('John Doe'); | |
jane = Person.new('Jane'); | |
// This returns a function object | |
john.sayHello; | |
// Properties that return a function can be called with parens | |
john.sayHello(jane); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NOTE: Backbone uses underscore not jQuery. | |
// Skip to the bottom of this function! | |
// --- | |
// Loads jQuery as the variable '$' | |
(function() { | |
// Load the script | |
var script = document.createElement("SCRIPT"); | |
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'; | |
script.type = 'text/javascript'; | |
document.getElementsByTagName("head")[0].appendChild(script); | |
// Poll for jQuery to come into existance | |
var checkReady = function(callback) { | |
if (window.jQuery) { | |
callback(jQuery); | |
} | |
else { | |
window.setTimeout(function() { checkReady(callback); }, 100); | |
} | |
}; | |
// Start polling... | |
checkReady(function($) { | |
// Use $ here... | |
}); | |
})(); | |
/// Defined Person.extend(otherObject) | |
var Person = { | |
sayHello: function (otherPerson) { | |
console.log("Hello, "+otherPerson.name+"!"); | |
}, | |
name: 'Anon', | |
new: function (name) { | |
this.name = name; | |
return this; | |
}, | |
extend: function(otherObject) { | |
return $.extend(otherObject, this); | |
} | |
} | |
var HardWorker = Person.extend({ | |
isReliable: true | |
}); | |
john = Person.new('John Doe'); | |
console.log(john.name+" is reliable: "+john.isReliable); | |
jane = HardWorker.new('Jane Doe') | |
console.log(jane.name+" is reliable: "+jane.isReliable); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment