Separating a `Backbone` collection (events issue) - javascript

So, the problem is next: I receive large collection of prices and there are prices for specific, let say, partners. Thus collection contains some kind of groups denoted by partner_id.
I filtering this collection (using collection.filter() in initialize method), to obtain different "format" of data for subsequent views.
var BasePrices = new Collections.ProductPrices( // Creating the same collection type
this.model.get('prices').filter(function (m) { // But a bit narrowed
return ~~m.get('partner_id') === 0; // leaving prices without `partner_id`
})
);
Later I pass this newly done collection to the view that is managing the list of base prices.
The problem itself is that I'm subscribing on events of this newly done collection, but events of models that remained there after .filter() are firing their events to the old collection that lays under this.model.get('prices'), but newly added models firing their events correctly (to the BasePrices collection).
I couldn't understand why its happening so. I can presume that there is smth. related with reference of model to collection (model.collection property), but why it is not updated when I created brand new collection and how to solve the issue?

If you're creating the filtered collection only to use it in a view, it is better (and more correct) to use the original collection and let the view render only the items you want. For example (inside the view class):
render: function() {
this.model.each(function(m) {
if(~m.get('partner_id') === 0)
return;
/* render m here */
});
}
The rationale is that the view represents the original collection.
(If you need several filtered views of the same collection, you can use a single view class for all of them and pass it a filter function:
initialize: function(filter) {
this.filter = filter;
}
render: function() {
this.model.each(function(m) {
if(!this.filter(m))
return;
/* render m here */
});
}
Then create a view like this: new FilteredView(function(m) {return ~~m.get('partner_id') === 0;})

And the problem was indeed in references and cloning (not cloning, actually). The point is that we need to clone everything to the new collection. Clone ... not copy, not pass (by reference as we know) - clone.
var BasePrices = new Collections.ProductPrices() // Creating the same collection type
_(this.model.get('prices').models) // Implicitly `_.chain`ing
.filter(function (m) { return ~~m.get('partner_id') === 0; }) // leaving prices without `partner_id`
.map(function (m) { return m.toJSON(); }) // converting each model to raw object
.tap(function (a) { c.add(a); }) // adding all models at once
.value(); // evaluating chain
! More elegant ways of solving this problem are highly appreciated.
UPD: Just to keep chaining consistent here is one-liner for lodash.
var BasePrices = _(this.model.get('prices').models)
.filter(function (m) { return ~~m.get('partner_id') === 0; })
.map(function (m) { return m.toJSON(); })
// creating collection passing all models in constructor
.thru(function (a) { return new Collections.ProductPrices(a); })
.value();

Related

VueJs Ajax Data Mapping

In a Vue page, I have a call to get data using Ajax when the mounted() event is fired. The code recreates the existing Pager using a new Pager object where it has to pass in all the parameters in the constructor to reconstruct it.
If I don't do this, vm.Pager is just an Object and does not have some needed methods, and fails the prop type check that it gets passed to.
axios.post("/Home/GetList", vm.Pager)
.then(function (result)
{
var p = result.data.Pager;
vm.Pager = new Pager(p.PageSize, p.CurrentRecord, p.TotalCount);
// etc. (Pager has additional fields...)
vm.ItemList = result.data.ListItems;
})
.catch(function (error)
{
alert(error);
});
In the knockoutjs, there was a mapping function and you could what tell it what types to map without having to recreate the object. This was convenient, particularly for more complicated or nested Ajax data.
Is there a better way to do this in Vue (or javascript) where it maps the type from the Ajax without having to recreate it?
You could make your own mapper function.
methods: {
mapTypesToData (responseData, map) {
responseData.forEach((item, key) => {
let mapperVal = map[key]
if (typeof mapperVal === 'string') {
this.$set(this, map[key], item)
} else if (typeof mapperVal === 'function') {
this.$set(this, key, map[key](item))
}
})
}
}
then in your ajax request
axios.post("/Home/GetList", vm.Pager)
.then(function (result)
{
this.mapTypesToData(result.data, {
ItemList: 'ListItems',
Pager: (p) => new Pager(p.PageSize, p.CurrentRecord, p.TotalCount)
})
})
I found I can use either:
Object.assign(vm.Pager, result.data.Pager);
Or
// import _ from 'lodash'
_.merge(vm.Pager, result.data.Pager);
...and both seem to update the viewmodel correctly. Unfortunately, when I use either of these methods, the watch method in the nested ListPager control (which receives the Pager object) does not fire.
To get that to work, I found the solution below, after looking at this documentation VueJs: Reactivity in Depth - Change Detection Caveats.
vm.Pager = Object.assign(new Pager(), vm.Pager, result.data.Pager);
This actually creates a new Pager but seems to populate it correctly and retains the Vue reactivity. Hopefully this will scale out to more elaborate solutions, if needed.

Different model types in one collection Backbone

Backbone 1.1.2
Underscore 1.7.0
jQuery 1.11.1
I have a single collection that holds messages.
My messages can be be of different types (and the endpoints in the api are different for each type, but I have an endpoint that allows me to do one request and get all the messages)
When Collection.fetch()
I need to be able to define which model to use when populating the collection based on existing properties.
I have tried as suggested here: A Backbone.js Collection of multiple Model subclasses
as well as the backbone documentation backbonejs.org
My code looks like this
model: function (attr, options) {
if(attr.hasOwnProperty('prop')){
return new PropModel(attr,options);
}
else if(attr.hasOwnProperty('another_prop')){
new AnotherPropModel(attr,options);
}
},
the attr value is just one big array of objects, so without traversing somehow this solution makes no sense to me and its obvious why it doesn't work.
Am I handling this correctly is there another way to do this?
---UPDATE----
I have also tried doing this in the Parse Function of the collection and my collection is just empty
parse: function (resp, options) {
_.each(resp, _.bind(function (r) {
console.log(this);
if(r.hasOwnProperty('prop')){
this.add(new PropModel(r));
}else{
this.add(new AnotherPropModel(r));
}
},this));
}
So the solution was a mix of using model function and return.
Here goes the explanation:
First off we have the parse function
which is just an entry point for us to alter a response that we receive from our server
parse: function (resp, options) {
return resp;
}
In my case, the server was returning an Object of Object as
{{1:data},{2:data}}
Firstly this is strange and obviously needs to be resolved.
The IMPORTANT POINT IS:
When backbone assess the response return from parse, it needs to decide where to break off for each model as in what defines a new model.
Backbone sees objects as a single model and as in my case, I had one big object, I was getting one big model... this is why the attrs argument in model function was one big mush of data.
So I simply altered my response in the parse function and Voila!! everything in model function worked as expected:
Here is the code:
model: function (attr, options) {
if(attr.hasOwnProperty('prop')){
return new PropModel(attr,options);
}
else if (attr.hasOwnProperty('anotherProp')){
return new AnotherPropModel(attr,options);
}
},
parse: function (resp, options) {
var response = [];
_.each(resp, _.bind(function (r) {
response.push(r);
},this));
return response;
}
Im sure there is a better way to resolve the object to array, but for now this works and I'm smiling again!!
This article lead me to the solution:
A collection of muppets
You could do something like the following - reacting to the different type (if possible) and then provide a different URL. Then once the JSON models are in the template, then you can render the HTML the way you like:
Example Json
"[{"id":1,"Type":"Person"},{"id":2,"Type":"Business"}]"
Example Model
var Person = Backbone.Model.extend({
keyTypes: {
Person: 'Person',
Business: 'Business'
},
url: function() {
// we are assuming only two types. Change logic if there are three or more types.
return this.get('Type') === this.keyTypes.Person ? '/api/people' : '/api/businesss';
}
});
Collection
var Collection = Backbone.Collection.extend({
model: Person
});
View
var View = Backbone.View.extend({
initialize: function() {
this.collection = new Collection()
.on('fetch', this.render, this);
},
bootstrap: function() {
this.collection.fetch();
}
render: function() {
this.$el.html(_.template({
models: this.collection.toJSON()
}));
}
})
** !! Update !! **
If you want to still use parse, it will could to look the following.
parse: function (data, options) {
var models = [];
_.each(data, function (entity) {
// this is IE8 Safe....
var model = Object.prototype.hasOwnProperty.call(entity,'prop') ? PropModel : AnotherPropModel;
models.push(new model(entity));
});
return models;
}

Backbone filtering

If I have a Backbone collection and want to create a copy of that collection with certain entries filtered out, how can I do that while keeping the copied instance as a Backbone.Collection?
Example:
​
var Module = Backbone.Model.extend();
var ModuleCollection = Backbone.Collection.​extend({
model: Module
});
​var modules = new ModuleCollection;
​modules.add({foo: 'foo'​​​​​​},{foo: 'bar'});​​​​​
console.log(modules instanceof Backbone.Collection); // true
var filtered = modules.filter(function(module) {
return module.get('foo') == 'bar';
});
console.log(filtered instanceof Backbone.Collection); // false
http://jsfiddle.net/m9eTY/
In the example above, I would like filtered to be a filtered version of modules, not just an array of models.
Essentially I would like to create a method in the collection instance that can filter out certain models and return the Backbone.Collection instance, but as soon as I start filtering the iteration methods returns an array.
You can wrap the filtered array in a temporary ModuleCollection if you want, the models filtered are the same instances of the ones in the original ModuleCollection, so if the module's attribute changes, it is still referenced by both collections.
so what I suggest you do is something like:
var filtered = new ModuleCollection(modules.filter(function (module) {
return module.get('foo') == 'bar';
}));
Since Backbone 0.9.2 there is an additional method called where that does the same:
var filtered = modules.where({foo: 'bar'});
that still returns an array though, so you will still need to wrap it as such:
var filtered = new ModuleCollection(modules.where({foo: 'bar'}));
For filtering collection using backbone
To make the filter you should have a filtered function in your collection
var MyCollection = Backbone.Collection.extend ({
filtered : function () {
I suggest to use UnderScore filter which will return true for valid and false for invalid where true is what you are looking for. use this.models to get the current collection models use model.get( '' ) to get the element you want to check for
var results = _.filter( this.models, function ( model ) {
if ( model.get('foo') == 'bar' )
return true ;
return false ;
});
Then use underscore map your results and transform it to JSON like this is probally where you are getting it wrong
results = _.map( results, function( model ) { return model.toJSON() } );
Finally returning a new backbone collection with only results this is how to make a copied collection
return new Backbone.Collection( results ) ;

How to make Backbone.js Collection items Unique?

Say I have these Backbone.js Model:
var Truck = Backbone.Model.extend({});
var truck1 = new Truck();
var truck2 = new Truck();
truck1.set("brand", "Ford");
truck2.set("brand", "Toyota");
truck3.set("brand", "Honda");
truck4.set("brand", "Ford");
Then, let's say we have a Backbone.js Collection:
var TruckList = Backbone.Collection.extend({
model: Truck,
comparator: function(truck) {
return truck.get("brand");
};
});
I'm a car collector, so time to add each car to my collection:
Trucks = new TruckList();
Trucks.add(truck1);
Trucks.add(truck2);
Trucks.add(truck3);
Trucks.add(truck4);
Just focusing on the brand attribute, truck4 is a duplicate of truck1. I can't have duplicates in my Collection. I need my collection to have unique values.
My question is, How do I remove duplicate items from my Backbone.js Collection?
Should I use Underscore.js for this? If so, can someone please provide a working/runnable example of how to do this.
Assume the following:
1.Collection is not sorted
Removal must be done on brand attribute value
Ajax call to populate each instance of a Truck. This means when adding to a collection, you don't have access to the Truck properties.
I would override the add method in your TruckList collection and use underscore to detect duplicates there and reject the duplicate. Something like.
TruckList.prototype.add = function(truck) {
// Using isDupe routine from #Bill Eisenhauer's answer
var isDupe = this.any(function(_truck) {
return _truck.get('brand') === truck.get('brand');
});
// Up to you either return false or throw an exception or silently ignore
// NOTE: DEFAULT functionality of adding duplicate to collection is to IGNORE and RETURN. Returning false here is unexpected. ALSO, this doesn't support the merge: true flag.
// Return result of prototype.add to ensure default functionality of .add is maintained.
return isDupe ? false : Backbone.Collection.prototype.add.call(this, truck);
}
The simplest way to achieve this is to make sure the models you are adding have unique ids. By default Backbone collections will not add models with duplicate ids.
test('Collection should not add duplicate models', 1, function() {
var model1 = {
id: "1234"
};
var model2 = {
id: "1234"
};
this.collection.add([model1, model2]);
equal(1, this.collection.length, "collection length should be one when trying to add two duplicate models");
});
Try this. It uses the any underscore method to detect the potential duplicate and then dumps out if so. Of course, you might want to dress this up with an exception to be more robust:
TruckList.prototype.add = function(newTruck) {
var isDupe = this.any(function(truck) {
return truck.get('brand') === newTruck.get('brand');
}
if (isDupe) return;
Backbone.Collection.prototype.add.call(this, truck);
}
As an aside, I would probably write a function on Truck to do the dupe checking so that the collection doesn't know too much about this condition.
var TruckList = Backbone.Collection.extend({
model : Truck,
// Using #Peter Lyons' answer
add : function(truck) {
// Using isDupe routine from #Bill Eisenhauer's answer
var isDupe = this.any(function(_truck) {
return _truck.get('brand') === truck.get('brand');
});
if (isDupe) {
// Up to you either return false or throw an exception or silently
// ignore
return false;
}
Backbone.Collection.prototype.add.call(this, truck);
},
comparator : function(truck) {
return truck.get("brand");
} });
VassilisB's answer worked great but it will override Backbone Collection's add() behavior. Therefore, errors might come when you try to do this:
var truckList = new TruckList([{brand: 'Ford'}, {brand: 'Toyota'}]);
So, I added a bit of a checking to avoid these errors:
var TruckList = Backbone.Collection.extend({
model : Truck,
// Using #Peter Lyons' answer
add : function(trucks) {
// For array
trucks = _.isArray(trucks) ? trucks.slice() : [trucks]; //From backbone code itself
for (i = 0, length = trucks.length; i < length; i++) {
var truck = ((trucks[i] instanceof this.model) ? trucks[i] : new this.model(trucks[i] )); // Create a model if it's a JS object
// Using isDupe routine from #Bill Eisenhauer's answer
var isDupe = this.any(function(_truck) {
return _truck.get('brand') === truck.get('brand');
});
if (isDupe) {
// Up to you either return false or throw an exception or silently
// ignore
return false;
}
Backbone.Collection.prototype.add.call(this, truck);
}
},
comparator : function(truck) {
return truck.get("brand");
}});
I'm doing a FileUpload thing with the same issue, and here's how I did it (coffeescript):
File = Backbone.Model.extend
validate: (args) ->
result
if !#collection.isUniqueFile(args)
result = 'File already in list'
result
Files = Backbone.Collection.extend
model: File
isUniqueFile: (file) ->
found
for f in #models
if f.get('name') is file.name
found = f
break
if found
false
else
true
... and that's it. The collection object is automatically referenced in File, and Validation is automatically called when an action is invoked on the collection which in this case is Add.
Underscore.js, a pre-req for backbone.js, provides a function for this: http://documentcloud.github.com/underscore/#uniq
Example:
_.uniq([1,1,1,1,1,2,3,4,5]); // returns [1,2,3,4,5]
Not sure if this is an update to either Backbone or underscore, but the where() function works in Backbone 0.9.2 to do the matching for you:
TruckList.prototype.add = function(truck) {
var matches = this.where({name: truck.get('brand')});
if (matches.length > 0) {
//Up to you either return false or throw an exception or silently ignore
return false;
}
Backbone.Collection.prototype.add.call(this, truck);
}
I would prefer override the add method like this.
var TruckList = Backbone.Collection.extend({
model : Truck,
// Using #Peter Lyons' answer
add : function(truck) {
// Using isDupe routine from #Bill Eisenhauer's answer
var isDupe = this.any(function(_truck) {
return _truck.get('brand') === truck.get('brand');
});
if (isDupe) {
// Up to you either return false or throw an exception or silently
// ignore
return false;
}
Backbone.Collection.prototype.add.call(this, truck);
},
comparator : function(truck) {
return truck.get("brand");
} });
It seems like an elegant solution would be to use _.findWhere so long as you have some unique attribute (brand in your case). _.findWhere will return a match which is a JavaScript object and therefore truthy or undefined which is falsey. This way you can use a single if statement.
var TruckList = Backbone.Collection.extend({
model: Truck,
add: function (truck) {
if (!this.findWhere({ brand: truck.get('brand') })) {
Backbone.Collection.prototype.add.call(this, truck);
}
}
});
Try this...
var TruckList = Backbone.Collection.extend({
model: Truck,
comparator: function(truck) {
return truck.get("brand");
},
wherePartialUnique: function(attrs) {
// this method is really only tolerant of string values. you can't do partial
// matches on arrays, objects, etc. use collection.where for that
if (_.isEmpty(attrs)) return [];
var seen = [];
return this.filter(function(model) {
for (var key in attrs) {
// sometimes keys are empty. that's bad, so let's not include it in a unique result set
// you might want empty keys though, so comment the next line out if you do.
if ( _.isEmpty(model.get(key).trim()) ) return false;
// on to the filtering...
if (model.get(key).toLowerCase().indexOf(attrs[key].toLowerCase()) >= 0) {
if (seen.indexOf( model.get(key) ) >= 0 ) return false;
seen.push(model.get(key));
return true;
} else {
return false;
}
}
return true;
});
}
});
A few things to remember:
this is based on the backbone.collection.where method and unlike that method, it will attempt partial matches on model attributes within a collection. If you don't want that, you'll need to modify it to only match exactly. Just mimic what you see in the original method.
it should be able to accept multiple attribute matches, so if you have model attributes of foo and bar, you should be able to do collection.wherePartialUnique({foo:"you",bar:"dude"}). I have not tested that though. :) I have only ever done one key/value pair.
i also strip out empty model attributes from consideration. I don't care about them, but you might.
this method doesn't require a collection of unique model properties that the comparator depends. It's more like a sql distinct query, but I'm not an sql guy so don't shoot me if that's a bad example :)
your collection is sorted by way of the comparator function, so one of your assumptions about it not being sorted is incorrect.
I believe this also addresses all of your goals:
Collection is not sorted
Removal must be done on brand attribute value
Ajax call to populate each instance of a Truck. This means when adding to a collection, you don't have access to the Truck properties.
I'm really unhappy with the accepted answer to this solution. It contains numerous errors. I've edited the original solution to highlight my concerns, but I am proposing the following solution assuming you're OK dirtying your duplicate's id/cid property:
TruckList.prototype.add = function(truckToAdd, options) {
// Find duplicate truck by brand:
var duplicateTruck = this.find(function(truck){
return truck.get('brand') === truckToAdd.get('brand');
});
// Make truck an actual duplicate by ID:
// TODO: This modifies truckToAdd's ID. This could be expanded to preserve the ID while also taking into consideration any merge: true options.
if(duplicateTruck !== undefined){
if(duplicateTruck.has('id')){
truckToAdd.set('id', duplicateTruck.get('id'), { silent: true });
}
else {
truckToAdd.cid = duplicateTruck.cid;
}
}
// Allow Backbone to handle the duplicate instead of trying to do it manually.
return Backbone.Collection.prototype.add.call(this, truckToAdd, options);
}
The only flaw with this one is that truckToAdd's ID/cid is not preserved. However, this does preserve all of the expected functionality of adding an item to a collection including passing merge: true.
I was not satisfied with the provided answers for several reasons:
Modifying the return value of add is unexpected.
Not supporting { merge: true } is unexpected.
I've provided a solution which I believe to be more robust. This solution clones given models if they have duplicates in the collection, updates the clones' ID to match the duplicates ID, and then passes the list of duplicates and non-duplicates onto the original add method so that it can do its magic. No unintended side-effects as far as I am aware.
add: function (models, options) {
var preparedModels;
if (models instanceof Backbone.Collection) {
preparedModels = models.map(this._prepareModelToAdd.bind(this));
}
else if (_.isArray(models)) {
preparedModels = _.map(models, this._prepareModelToAdd.bind(this));
} else if (!_.isNull(models) && !_.isUndefined(models)) {
preparedModels = this._prepareModelToAdd(models);
} else {
preparedModels = models;
}
// Call the original add method using preparedModels which have updated their IDs to match any existing models.
return Backbone.Collection.prototype.add.call(this, preparedModels, options);
},
// Return a copy of the given model's attributes with the id or cid updated to match any pre-existing model.
// If no existing model is found then this function is a no-op.
// NOTE: _prepareModel is reserved by Backbone and should be avoided.
_prepareModelToAdd: function (model) {
// If an existing model was not found then just use the given reference.
var preparedModel = model;
var existingModel = this._getExistingModel(model);
// If an existing model was found then clone the given reference and update its id.
if (!_.isUndefined(existingModel)) {
preparedModel = this._clone(model);
this._copyId(preparedModel, existingModel);
}
return preparedModel;
},
// Try to find an existing model in the collection based on the given model's brand.
_getExistingModel: function (model) {
var brand = model instanceof Backbone.Model ? model.get('brand') : model.brand;
var existingModel = this._getByBrand(brand);
return existingModel;
},
_getByBrand: function (brand) {
return this.find(function (model) {
return model.get('brand') === brand;
});
},
_clone: function (model) {
// Avoid calling model.clone because re-initializing the model could cause side-effects.
// Avoid calling model.toJSON because the method may have been overidden.
return model instanceof Backbone.Model ? _.clone(model.attributes) : _.clone(model);
},
// Copy the model's id or cid onto attributes to ensure Backbone.Collection.prototype.add treats attributes as a duplicate.
_copyId: function (attributes, model) {
if (model.has('id')) {
attributes.id = model.get('id');
} else {
attributes.cid = model.cid;
}
}

Creating methods on the fly

Hi I'm trying to author a jQuery plugin and I need to have methods accessible to elements after they are initialized as that kind of object, e.g.:
$('.list').list({some options}); //This initializes .list as a list
//now I want it to have certain methods like:
$('.list').find('List item'); //does some logic that I need
I tried with
$.fn.list = function (options) {
return this.each(function() {
// some code here
this.find = function(test) {
//function logic
}
}
}
and several other different attempts, I just can't figure out how to do it.
EDIT:
I'll try to explain this better.
I'm trying to turn a table into a list, basically like a list on a computer with column headers and sortable items and everything inbetween. You initiate the table with a command like
$(this).list({
data: [{id: 1, name:'My First List Item', date:'2010/06/26'}, {id:2, name:'Second', date:'2010/05/20'}]
});
.list will make the <tbody> sortable and do a few other initial tasks, then add the following methods to the element:
.findItem(condition) will allow you to find a certain item by a condition (like findItem('name == "Second"')
.list(condition) will list all items that match a given condition
.sort(key) will sort all items by a given key
etc.
What's the best way to go about doing this?
If you want these methods to be available on any jQuery object, you will have to add each one of them to jQuery's prototype. The reason is every time you call $(".list") a fresh new object is created, and any methods you attached to a previous such object will get lost.
Assign each method to jQuery's prototype as:
jQuery.fn.extend({
list: function() { .. },
findItem: function() { .. },
sort: function() { .. }
});
The list method here is special as it can be invoked on two occasions. First, when initializing the list, and second when finding particular items by a condition. You would have to differentiate between these two cases somehow - either by argument type, or some other parameter.
You can also use the data API to throw an exception if these methods are called for an object that has not been initialized with the list plugin. When ('xyz').list({ .. }) is first called, store some state variable in the data cache for that object. When any of the other methods - "list", "findItem", or "sort" are later invoked, check if the object contains that state variable in its data cache.
A better approach would be to namespace your plugin so that list() will return the extended object. The three extended methods can be called on its return value. The interface would be like:
$('selector').list({ ... });
$('selector').list().findOne(..);
$('selector').list().findAll(..);
$('selector').list().sort();
Or save a reference to the returned object the first time, and call methods on it directly.
var myList = $('selector').list({ ... });
myList.findOne(..);
myList.findAll(..);
myList.sort();
I found this solution here:
http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html
This seems to do exactly what I need.
(function($) {
var TaskList = function(element, options)
{
var $elem = $(element);
var options = $.extend({
tasks: [],
folders: []
}, options || {});
this.changed = false;
this.selected = {};
$elem.sortable({
revert: true,
opacity: 0.5
});
this.findTask = function(test, look) {
var results = [];
for (var i = 0,l = options.tasks.length; i < l; i++)
{
var t = options['tasks'][i];
if (eval(test))
{
results.push(options.tasks[i]);
}
}
return results;
}
var debug = function(msg) {
if (window.console) {
console.log(msg);
}
}
}
$.fn.taskList = function(options)
{
return this.each(function() {
var element = $(this);
if (element.data('taskList')) { return; }
var taskList = new TaskList(this, options);
element.data('taskList', taskList);
});
}
})(jQuery);
Then I have
$('.task-list-table').taskList({
tasks: eval('(<?php echo mysql_real_escape_string(json_encode($tasks)); ?>)'),
folders: eval('(<?php echo mysql_real_escape_string(json_encode($folders)); ?>)')
});
var taskList = $('.task-list-table').data('taskList');
and I can use taskList.findTask(condition);
And since the constructor has $elem I can also edit the jQuery instance for methods like list(condition) etc. This works perfectly.
this.each isn't needed. This should do:
$.fn.list = function (options) {
this.find = function(test) {
//function logic
};
return this;
};
Note that you'd be overwriting jQuery's native find method, and doing so isn't recommended.
Also, for what it's worth, I don't think this is a good idea. jQuery instances are assumed to only have methods inherited from jQuery's prototype object, and as such I feel what you want to do would not be consistent with the generally accepted jQuery-plugin behaviour -- i.e. return the this object (the jQuery instance) unchanged.

Categories

Resources