Last active
December 20, 2015 02:49
-
-
Save watert/6059437 to your computer and use it in GitHub Desktop.
for filter query dom setting & listening.
This file contains 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
/** | |
* QueryModel based on jQuery,momentjs,backbonejs. | |
* usage: | |
* // _GET = {"pre_key":"value","pre_key2":"value2"}; | |
* var query = new QueryModel(_GET,{prefix:"pre"}); | |
* // console.log(query.toJSON()); | |
* // Object {key: "value", key2: "value2"} | |
* // console.log(query.getUrl()) | |
* // "http://localhost/path/?key=value&key2=value2" | |
*/ | |
QueryModel = Backbone.Model.extend({ | |
clearPrefixAttributes:function(){ | |
var that = this; | |
_.each(this.toJSON,function(item,key){ | |
if(key.indexOf&&key.indexOf(that.prefix+"_")==0){ | |
that.unset(key); | |
} | |
}); | |
}, | |
encodePrefix:function(json,prefix){ | |
var that = this; | |
var obj = {}; | |
if(!prefix){ | |
prefix=json; | |
obj=this.toJSON(); | |
}else { | |
_.each(json,function(item,key){ | |
if(key.indexOf(prefix+"_")==0){ | |
var okey = key.slice(prefix.length+1); | |
obj[okey] = item; | |
} | |
}); | |
}; | |
return obj; | |
}, | |
decodePrefix:function(){ | |
var json = this.toJSON(), | |
that = this, | |
prefix = this.prefix, | |
obj = {}; | |
if(!this.prefix)return json; | |
var json2= _.object(_.filter(_.pairs(json),function(p){ | |
var k =p[0], | |
v=p[1]; | |
return that.defaults[k]!=v; | |
})); | |
_.each(json2,function(item,key){ | |
obj[prefix+"_"+key] = item; | |
}); | |
return obj; | |
}, | |
defaults:{}, | |
initialize:function(json,options){ | |
var prefix = options&&options.prefix||null; | |
this.prefix = prefix; | |
if(prefix){ | |
this.clearPrefixAttributes(); | |
json = this.encodePrefix(json,prefix); | |
} | |
this.clear(); | |
this.set(this.defaults); | |
this.set(json); | |
var data = this.decodePrefix(); | |
}, | |
getUrl:function(){ | |
var query = this.toJSON(); | |
if(query.startTime==this.defaults.startTime)delete query.startTime; | |
if(query.endTime==this.defaults.endTime)delete query.endTime; | |
var base = location.href.split("?")[0]; | |
var url = base + "?" + $.param(query); | |
return url; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment