JavaScript small tip, HTML5 History API, history.js
Blogs20142014-04-21
1. JavaScript: constructor functions instantiation
With a constructor function, there are different ways to do the instantiation.
var Person = function(name) { this.name = name; }
Person.prototype.getName = function() { return this.name;}
//1.
var o={}
Person.apply(o, ['william'])
//2.
var p = new Person('bill')
// make object 'o', 'p' same behavior
p.getName(); //"bill"
o.getName(); //TypeError: undefined is not a function
o.__proto__ = Person.prototype;
o.getName(); //"william"
//3. use __proto__ and constructor.prototype:
var o2 = {}
Person.call(o2, 'test');
o2.__proto__ = p.constructor.prototype;
o2.getName(); //'test'2. HTML5 History API (commonly known as pushState)
According to Mozilla, The DOM window object provides access to the browserâs history through the window.history object. Such as âMoving forward and backwardâ, âMoving to a specific point in historyâ etc by using:
window.history.back();
window.history.forward();
history.go(-1); //back
history.go(1); //forward
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");For Backbone.js, it is: Backbone.history.start({ pushState: true }); For jQuery, use: history.js:
History.js gracefully supports the HTML5 History/State APIs (pushState, replaceState, onPopState) in all browsers. Including continued support for data, titles, replaceState. Supports jQuery. For HTML5 browsers this means that you can modify the URL directly, without needing to use hashes anymore.
Using âhistory.jsâ with jQuery, it will enable the url back and forward, very cool.
