I am using DeepModel to access nested attributes in a Backbone.js model. So this works fine:
this.model.set({'chart_configs.mentions_bar_graph.date': "cats"});
However, I'd like to use a variable as part of my key so like:
this.model.set({'chart_configs.'+ this.chartName + '.date': "cats"});
Is this some how possible? I know that I can do it by
this.model.attributes.chart_configs["mentions_bar_graph"].date = "cats";
But that, obviously, does not trigger a "change" event else where in my code.
thanks!
Model#set can be called in two ways:
m.set('key', 'value');
m.set(an_object_of_keys_and_values);
So you should be able to get past the "you can't define an object literal like that" problem by using the first form of Model#set:
this.model.set('chart_configs.' + this.chartName + '.date', 'cats');
If DeepModel doesn't like that then you could do it the long way:
var values = { };
values['chart_configs.' + this.chartName + '.date'] = 'cats';
this.model.set(values);
An object is an object whether it has a name or not and set only cares about the keys and values.
Related
I have a copy button that has:
$scope.copyHeadline = function (headline) {
var headlineCopy = headline;
var current_time = Date.now();
headlineCopy.label = headline.label + ' (Copy ' + current_time + ')';
$scope.headlineList.push(headlineCopy);
}
but I get the "Duplicates in a repeater are not allowed" error. I notice that everyone element in the array or list that i have has some sort of hidden property like:
$$hashKey: "object:135"
which i'm pretty sure is what it's duplicating but I can't change?
I read that I can use:
track by $index
but what ends up happening is that when I push the Copy button, it also edits the original element that I was copying as well so that doesn't work..
I was also of thinking of just creating a whole new element and writing a function that'll literally copy every element into a new one.. but this Class alone has several subclasses with ALOT of properties. So i guess I just wanted to see if there was an easier of doing it before I resort to that method. Thanks!
That is happening because just assigning a reference of the original object to a different variable will not make a copy of it. It just copies the reference to the same object.
AngularJS copy documentation
Use:
var headlineCopy = angular.copy(headline);
This will make a deep copy of the object.
Your problem stems from the fact that you are not copying your headline object, merely referencing it.
It's difficult to know the full solution without knowing more about your headline objects, but you could try something like this:
$scope.copyHeadline = function (headline) {
var headlineCopy = {};
var current_time = Date.now();
headlineCopy.label = headline.label + ' (Copy ' + current_time + ')';
$scope.headlineList.push(headlineCopy);
}
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
Creating a JavaScript global array with static elements?
The problem isn't that removeFunction doesn't have access to bigArray. The problem is in your onclick attribute, and the id you're putting on the link:
$('#div').append("<a href='#' id='bigArray[i]' onclick='removeFunction(bigArray[i])'>Element bigArray[i]</a><br />");
In the onclick, you're referring to i, but A) I'm guessing i isn't a global, and B) Even if it is, it will not have the value of i that you used to render that row. The code will look for the value of a global i variable as of when the link is clicked.
Separately, you're creating multiple elements with the same id value, which is bigArray[i] (not bigArray[0], bigArray[1], etc.)
You could use the value instead, like this:
$('#div').append("<a href='#' id='bigArray[" + i + "]' onclick='removeFunction(" + i + ")'>Element bigArray[i]</a><br />");
The changes there are:
For the id, I changed it to: "...id='bigArray[" + i + "]'", which will output id='bigArray[0]', then id='bigArray[1]', etc., instead of repeatedly outputting id='bigArray[i]' (literally.
I just pass the index into removeFunction, again by putting the value there, not a reference to the variable i: "... onclick='removeFunction(" + i + ")' ..."
Then your removeFunction would be:
function removeFunction(i) { // <== i, not id
bigArray.splice(i, 1); // <== real code, not pseudocode
renderArray(bigArray);
}
I would not recommend doing it that way, but it's the minimal fix.
There's no need to pass bigArray to anything. It's a global.
FWIW, I would recommend refactoring so you don't have to re-render the whole thing every time.
Define a variable at the global scope first that will hold your "bigArray", then assign the value to it once you receive the data through your ajax call.
var bigArray;
$.ajax({
bigArray = bigArrayFromAjax;
renderArray(bigArray);
});
... then your other functions should have access to it.
Jquery Each Json Values Issue
This question is similar to above, but not the same before it gets marked duplicated.
After realasing how to use computed values i came across another issue.
In my javascript i have the following code:
var incidentWizard = ['page1.html','page2.html','page3.html'];
var magicWizard = ['page1.html','page2.html','page3.html'];
var loadedURL = 'page1.html';
The input to this function would be (true,'incident')
function(next,wizardname)
{
var WizSize = incidentWizard.length;
wizardName = [wizardName] + 'Wizard';
var wizardPOS = jQuery.inArray(loadedURL,incidentWizard);
And now i want to use the wizardname parameter to decide what array i am going to use...
Loader(incidentWizard[wizardPOS],true);
Ive also tried
Loader([incidentWizard][wizardPOS],true);
and
Loader([incidentWizard][wizardPOS],true);
Also the loader function just required the string value in the array at wizardPOS sorry for confusion
But when trying this i always end up with the outcome...
/incidentWizard
I know this is something to do with using computed values but i've tried reading about them and cant seem to solve this issue.
Basicly i want to use the computed value of wizardName to access an an array of that name.
Please help supports, looking forward to seeing many ways to do this!
On this line:
wizardName = [wizardName] + 'Wizard';
You are attempting to concatenate the string 'Wizard' to an Array with one string element "incident". I'm assuming you just want regular string concatenation:
wizardName = wizardName + 'Wizard';
However, now you only have a string, not an array instance. To fix that, change the way you define your *Wizard arrays to something like:
var wizardyThings = {
incidentWizard : ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then your function (which is missing a name as it stands), becomes:
function someMethod(next, wizardname) {
wizardName = wizardName + 'Wizard';
var wizSize = wizardyThings[wizardName].length;
var wizardPOS = jQuery.inArray(loadedURL, wizardyThings[wizardName]);
...
}
You can only access properties of objects that way. For global values, window[ name ] will work. For simple local variables it's just not possible at all. That is, if inside a function you've got
var something;
then there's no way to get at that variable if all you have is the string "something".
I would just put each array as a prop on an object:
var obj {
incidentWizard: ['page1.html','page2.html','page3.html'],
magicWizard: ['page1.html','page2.html','page3.html']
};
Then you can just do obj['incidentWizard'] or obj.incidentWizard this will return:
['page1.html','page2.html','page3.html']
A simple question I'm sure, but I can't figure it out.
I have some JSON returned from the server
while ($Row = mysql_fetch_array($params))
{
$jsondata[]= array('adc'=>$Row["adc"],
'adSNU'=>$Row["adSNU"],
'adname'=>$Row["adname"],
'adcl'=>$Row["adcl"],
'adt'=>$Row["adt"]);
};
echo json_encode(array("Ships" => $jsondata));
...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...
if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
{
WShipsObject = JSON.parse(ajaxRequest.responseText);
var eeWShips = document.getElementById("eeWShipsContainer");
for (i=0;i<WShipsObject.Ships.length;i++)
{
newElement = WShipsObject.Ships;
newWShip = document.createElement("div");
newWShip.id = newElement[i].adSNU;
newWShip.class = newElement[i].adc;
eeWShips.appendChild(newWShip);
} // end for
}// If
You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...
I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.
So how do I do this?
Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...
$(".wShip").click(function(){
var test1 = $.inArray(this.id, newElement.test);
var test2 = $.inArray(this.id, WShipsObject);
//alert(test1+"\n"+test2+"\n"+this.id);
});
For one you can simply use the ID attribute of the DIV to store a unique string, in your case it could be the index.
We do similar things in Google Closure / Javascript and if you wire up the event in the loop that you are creating the DIV in you can pass in a reference to the "current" object.
The later is the better / cleaner solution.
$(".wShip").click(function(){
var id = $(this).id;
var result;
WShipsObject.Ships.each(function(data) {
if(data.adSNU == id) {
result = data;
}
});
console.log(result);
}
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.
In the solution I created a custom attribute called key into which I stored the index.
newWShip.key = i;
Later when I need the index back again I can use this.key inside the JQuery .click()method:
var key = this.key;
var adt = WShipsObject.Ships[key].adt;
You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.