This is the same question as this:
https://stackoverflow.com/questions/2890620/jquery-running-a-function-in-a-context-and-adding-to-a-variable
But that question was poorly posed.
Trying again, I'm trying to do something like this:
I have a bunch of elements I want to grab data from, the data is in the form of classes of the element children.
<div id='container'>
<span class='a'></span>
<span class='b'></span>
<span class='c'></span>
</div>
<div id='container2'>
<span class='1'></span>
<span class='2'></span>
<span class='3'></span>
</div>
I have a method like this:
jQuery.fn.grabData = function(expr) {
return this.each(function() {
var self = $(this);
self.find("span").each(function (){
var info = $(this).attr('class');
collection += info;
});
});
};
I to run the method like this:
var collection = '';
$('#container').grabData();
$('#container2').grabData();
The collection should be adding to each other so that in the end I get this
console.log(collection);
:
abc123
But collection is undefined in the method. How can I let the method know which collection it should be adding to?
Thanks.
If you want to accumulate values for every call of the grabData function you will need a global variable:
var collection = '';
jQuery.fn.grabData = function(expr) {
return this.each(function() {
var self = $(this);
self.find('span').each(function () {
var info = $(this).attr('class');
collection += info;
});
});
};
If on the other hand you want to do it only for single call of the grabData function you could do this:
jQuery.fn.grabData = function(expr) {
var collection = '';
this.each(function() {
var self = $(this);
self.find('span').each(function () {
var info = $(this).attr('class');
collection += info;
});
});
return collection;
};
And then use it like this:
var collection = $('#container').grabData();
console.log(collection);
Related
Hello I've used this patter to get a static variable
var uniqueID = (function() {
var id = 0; // This is the private persistent value
// The outer function returns a nested function that has access
// to the persistent value. It is this nested function we're storing
// in the variable uniqueID above.
return function() { return id++; }; // Return and increment
})(); // Invoke the outer function after defining it.
Now I'm trying to clone this function, but backup and the original still return sequential values. How can i "freeze" the status of the function when copy it?
Thanks
OK, something like this extremely convoluted contraption should work (fiddle, http://jsfiddle.net/dPLj6/):
var uniqueIdFunction = function(initialValue) {
var id = initialValue || 0;
var result = function() { return id++; };
result.clone = function(){ return uniqueIdFunction(id); }
return result;
};
var uniqueId1 = uniqueIdFunction();
Use the clone method to get a clone. The original will keep it's own internal id value. The clone will take its initial internal id from the clone source.
Here is a function that generates unique id generators:
var createGenerator = function(id) {
var id = id || 0;
return function() { return id++; };
}
var g1 = createGenerator();
var g2 = createGenerator();
console.log(g1(), g1(), g1());
console.log(g2(), g2());
console.log(g1());
console.log(g2());
// OP's cloning scenario
var freezeId = g1();
var clone = createGeenrator(freezeId);
console.log(g1(),g1());
console.log(clone());
#pax162's answer is more in line with what the OP wants to do. I just decided to post the more normal way of doing it.
I am building a sidebar to filter a main view, like for instance the one at John Lewis. I have the code working but it ain't pretty.
I know there are several SO questions on similar lines but I can't quite fathom my own use case.
I need to get the names of the checkboxes from the server ( eg via JSON ) to dynamically create observableArrays on my ShopView.
Here's how it is:
var data = {
'gender' : [ ],
'color' : [ ]
};
var filterMapping = {
create: function( obj ) {
return ko.observableArray( obj.data );
}
}
var ShopView = new function() {
var self = this;
ko.mapping.fromJS( { filters: data }, filterMapping, self );
// this is the bit I don't like
this.filterChange = ko.computed(function () {
for( var key in self.filters ) {
var obj = self.filters[key];
if( ko.isObservable(obj)){
obj();
}
}
});
this.filterChange.subscribe( function( ) {
//make AJAX request for products using filter state
});
}
My HTML looks as you'd expect:
Gender
<ul>
<li><input type="checkbox" value="male" data-bind="checked: filters.gender" />Male</li>
<li><input type="checkbox" value="female" data-bind="checked: filters.gender" />Female</li>
</ul>
As I say, it works, but it's not nice. In an ideal world I could subscribe to this.filters, eg
this.filters.subscribe( function() {
//make AJAX request for products using filter state
});
NB I'm not trying to do the filtering on the client side - just update my viewmodel when the dynamically-bound checkboxes change.
Any ideas? thanks!
First, the mapping plugin should be treated as an aid to code duplication. I don't think its a good idea to think of the mapping plugin as a solution in and of itself; at least not directly. It also obscures what is happening when you post your code on SO, since we can't see the models you are working with. Just a thought.
Now, ff you want to get dynamic filters from the server, and use them to filter a list of items (like you would in a store), I would do it something like this (here is the fiddle):
var FilterOption = function(name) {
this.name = name;
this.value = ko.observable(false);
};
var Filter = function(data) {
var self = this;
self.name = data.name;
options = ko.utils.arrayMap(data.options, function(o) {
return new FilterOption(o);
});
self.options = ko.observableArray(options);
self.filteredOptions = ko.computed(function() {
var options = []
ko.utils.arrayForEach(self.options(), function(o) {
if (o.value()) options.push(o.name);
});
//If no options, false represents no filtering for this type
return options.length ? options : false;
});
};
var ViewModel = function(data) {
var self = this;
self.items = ko.observableArray(data.items);
filters = ko.utils.arrayMap(data.filters, function(i) {
return new Filter(i);
});
self.filters = ko.observableArray(filters);
self.filteredItems = ko.computed(function() {
//Get the filters that are actually active
var filters = ko.utils.arrayFilter(self.filters(), function(o) {
return o.filteredOptions();
});
//Remove items that don't pass all active filter
return ko.utils.arrayFilter(self.items(), function(item) {
var result = true;
ko.utils.arrayForEach(filters, function(filter) {
var val = item[filter.name.toLowerCase()];
result = filter.filteredOptions().indexOf(val) > -1;
});
return result;
});
});
};
The next obvious step would be to add support for items that had multiple properties, but or options properties, but this should give you the basic idea. You have a list of filters, each with any number of options (which stack additively), and you use a computed items array to store the result of filtering the items.
Edit: To get the items using an ajax subscription, you would replace the FilteredItems prop with a computed that gets the selected filters, and then subscribe to it, like this:
var ViewModel = function(data) {
var self = this;
self.items = ko.observableArray(data.items);
filters = ko.utils.arrayMap(data.filters, function(i) {
return new Filter(i);
});
self.filters = ko.observableArray(filters);
self.selectedFilters = ko.computed(function() {
ko.utils.arrayFilter(self.filters(), function(o) {
return o.filteredOptions();
});
});
self.selectedFilters.subscribe(function() {
//Ajax request that updates self.items()
});
};
I'm trying to use a computed observable to create a custom div ID (e.g. branch3). However, anytime I attempt to bind the computed I get the "unable to parse bindings" error. I'm sure I could just go about doing this a different way, but I just don't understand why I can't use a computed here. I'm pretty sure I've seen it done.
Here is the jsfiddle I've been working on.
FIDDLE
var branchList =[{"Id":1,"Latitude":40.2444400000,"Longitude":-111.6608300000,"StreetAddress":"1525 W 820 N","BranchName":"GPS","City":"Cityplacwe","State":"UT","Zip":"84601"},{"Id":2,"Latitude":40.2455550000,"Longitude":-111.6616100000,"StreetAddress":"123 N Center","BranchName":"GPS Branch 2","City":"Lehi","State":"UT","Zip":"84043"}];
//myMarkers = new Array();
var Branch = function (data) {
var self = this;
self.Id = ko.observable(data.Id);
self.Latitude = ko.observable(data.Latitude);
self.Longitude = ko.observable(data.Id);
self.BranchName = ko.observable(data.BranchName);
self.StreetAddress = ko.observable(data.StreetAddress);
self.City = ko.observable(data.City);
self.State = ko.observable(data.State);
self.Zip = ko.observable(data.Zip);
this.DivId = ko.computed(function () {
return self.Id();
});
//self.DivId = ko.computed({
// //Reading from object to field
// read: function () {
// return "branch" + self.Id();
// },
// //writing from field to object
// write: function (value) {
// }
//});
}
var BranchViewModel = function () {
var self = this;
//create knockout array
self.branchArrayKO = ko.observableArray(branchList);
}
And the HTML
<div data-bind="foreach: branchArrayKO">
<div data-bind="attr: {'id': DivId}">
<p></p>
<h2></h2>
<ul>
<li data-bind="text: Id"></li>
<li data-bind="text: BranchName"></li>
<li data-bind="text: StreetAddress"></li>
</ul>
</div>
</div>
You need to convert your raw JavaScript array into an array of Branches. One way to do this is to use ko.utils.arrayMap to iterate over each item in the list and create a new Branch:
var BranchViewModel = function() {
var self = this;
//create knockout array
self.branchArrayKO = ko.observableArray(ko.utils.arrayMap(branchList, function(branch) {
return new Branch(branch);
}));
}
Updated example: http://jsfiddle.net/hawMW/2/
Another alternative that might be useful is the knockout mapping plugin, which you can use to automate all or part of the mapping process.
I have a couple click functions with jQuery that share the same variables, so I created a function to return those variables.
While this works, I'm wondering whether programmatically speaking this is the right or most efficient way to do this:
function clickVars($me){
var $curStep = $('.cust-step-cur'),
$nextStep = $curStep.next('.cust-step'),
nextStepLen = $nextStep.length,
$list = $('.cust-list'),
$btnCheck = $('.cust-btn.checklist'),
hasChecklist = $me.hasClass('checklist');
return {
curStep: $curStep,
nextStep: $nextStep,
nextStepLen: nextStepLen,
list: $list,
btnCheck: $btnCheck,
hasChecklist: hasChecklist
};
}
// Checklist Click
$('.option-list a').on('click',function(){
var $me = $(this),
myVars = clickVars($me);
currentStepOut(myVars.curStep);
myVars.curStep.removeClass('cust-step-cur');
currentStepIn(myVars.nextStep, myVars.list, myVars.btnCheck);
});
// Navigation
$('.cust-btn').on('click',function(){
if(animReady === false)
return false;
var $me = $(this),
myVars = clickVars($me);
if(myVars.hasChecklist && myVars.list.hasClass('cust-step-cur'))
return false;
currentStepOut(myVars.curStep);
myVars.curStep.removeClass('cust-step-cur');
if(myVars.nextStepLen === 0 || $me.hasClass('checklist')) {
myVars.nextStep = myVars.list;
}
animReady = false;
currentStepIn(myVars.nextStep, myVars.list, myVars.btnCheck);
});
Is this a standard way of generated shared variables between multiple functions?
In AS3 it's good practice to do:
// Variable definitions
var enabled:Boolean = false;
public function myFunction(){
enabled = true;
}
So in JavaScript I've been doing:
// Variable defintions
var a,b,c,d,e = 0;
function alterVariables(){
a = 1;
b = 2;
}
You have to understand you are not sharing variables between functions. Moreover, each time you click those elements, clickVars function is called again and again, even if you click only one element multiple times. So this code is very bad expirience. Check this:
// Defined ones
var nodes = {
$elements : $('.elements'),
$otherElements : $('.otherElements'),
}
// In case you have multiple .selector elements in your DOM
$('.selector').each(function() {
// Defined ones for each element
var $element = $(this), isList = $element.hasClass('.list');
$element.bind('click', function(){
nodes.$elements.addClass('clicked');
});
});
$('.anotherSelector').each(function() {
// Yep, here is some duplicate code. But there won't be any
// performance improvement if you create special method for
// such small piece of code
var $element = $(this), isList = $element.hasClass('.list');
$element.bind('click', function(){
nodes.$elements.addClass('clicked');
});
});
In the context of the code below (or anywhere), is it possible for a getelementbyid function to work plurally? Or do I need a different function, or possibly Jquery?
<script type="text/javascript">
window.onload = function()
{
var test = document.getElementById('test');
if (test)
{
test.className = 'unactive';
test.firstChild.onclick = function()
{
if(this.parentNode.className == 'unactive') {
this.parentNode.className = 'active';
}
else
{
this.parentNode.className = 'unactive';
}
}
}
};
</script>
You can use this;
document.getAllById = function(id){
if(document.all)
return document.all[id];
var elements = [],
all = document.getElementsByTagName('*');
for(var i=0;i<all.length;i++)
if(all[i].getAttribute('id')===id)
elements.push(all);
return elements;
}
Anyway, as #Pointy said, the id attribute is supposed to be unique, while class is used to define one or more elements that has some common properties
I assume you want to act on multiple elements using a list of IDs. (If I am wrong, and you actually want to select multiple elements with the same ID, you have done a Bad Thing, since IDs should be unique. In that case, you should use classes instead.)
In jQuery, you can accomplish this with a comma-separated list of id selectors (like $("#foo, #bar, #baz")) and implement your function like:
$("#foo, #bar, #baz").addClass("unactive")
.children(":first-child").click(function() {
var $this = $(this);
var $parent = $this.parent();
$parent.toggleClass("active unactive");
});
Without jQuery, this small function takes a list of IDs and results an array of nodes:
document.getElementsByIdList() {
var results = [];
for(var i=0; i<arguments.length; ++i) {
results.push(document.getElementById(arguments[i]));
}
return results;
}
Use it with you current code with:
var myNodeArray = document.getElementsByIdList("foo", "bar", "baz");
for(var i=0; i<myNodeArray.length; ++i) {
var test = myNodeArray[i];
if(test) {
// your code goes in here...
}
}