In an object I have a method where I want to get some information from a server(JSON format). I want to add this data to my object where the function is (By using a setter).
The problem is that this isn't my object but the jquery callback. How could/should I solve this?
function anObject() {
$.get(URL, doTheCallback);
function setExample(example) {
this.example = example;
}
function doTheCallback(data) {
this.setExample(data.results[0].example);
}
}
You can use bind:
$.get(URL,doTheCallback.bind(this));
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
Or assign your scope in a variable like:
function anObject() {
var that = this;
$.get(URL, doTheCallback);
function setExample(example) {
that.example = example;
}
function doTheCallback(data) {
that.setExample(data.results[0].example);
}
}
If you switched to $.ajax, you can use the context option.
function anObject() {
$.ajax(URL, {context: this}).done(doTheCallback);
function setExample(example) {
this.example = example;
}
function doTheCallback(data) {
this.setExample(data.results[0].example);
}
}
Related
I'm quite sure this question has been asked before, but I couldn't find anything related to my case.
Here's my function
function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange = change;
blur.onchange = change;
I'm struggling with passing argument to change function, because if I do spacing.onchange = change("prop") the function will be executed immediately. I want to avoid using addEventListener. So here's the question, how can I pass an argument to my function?
You can solve that by using high order function feature
function change(prop) {
return function() {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
}
// for example
spacing.onchange = change(/*Your prop*/);
blur.onchange = change(/*Your prop*/);
spacing.onchange = change.bind(spacing, 'prop');
Try setting the variable equal to the function definition.
spacing.onchange = function change(prop) {
document
.querySelector("img")
.style.setProperty(`--${prop}`, `${this.value}px`);
}
spacing.onchange(arg);
Try this:
function onChanges (variables,props) {
variables.forEach((variable, index) => {
variable.onChange=function(event){
return change(props[index]);
}
});
}
onChanges([spacing,blur],[prop1,prop2]);
I want to call a JavaScript function that I made after a JQuery event has been called. I defined a function called scrambleDot earlier like this var scrambleDot = new function()
{ //my code }. Here's the code that I tried to use:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
$('scrambleDot');
})
})
You have to call it just like:
scrambleDot();
To define a function, you don't need the new operator, so you should have:
var scrambleDot = function() { //my code }
If it still throws an error, it means it was defined in other scope. To make it globally accesible, do this when defining it:
window.scrambleDot = function() { //my code }
Cheers
We have to use new keyword, only when the function is used as a constructor for new Objects. So, the definition should not use new.
var scrambleDot = function() { //my code }
If the function need not be created dynamically, I would recommend
function scrambleDot() {
...
}
To invoke the function, simply do
scrambleDot();
For that call the function instead of selecting an element as:
$('#reveal').click(function() {
$('.cover').css({'visibility':'hidden'});
$('#under').css({'visibility':'visible'});
})
$('#conceal').click(function() {
scrambleDot();
});
And also, you write functions as:
function scrambleDot () {
// your code
}
It is a better practice than the variable one.
So here's the object 'playerTurnObj'
function playerTurnObj(set_turn) {
this.playerTurn=set_turn;
function setTurn(turnToSet) {
this.playerTurn=turnToSet;
}
function getTurn() {
return this.playerTurn;
}
}
and here is what I'm doing with it
var turn = new playerTurnObj();
turn.setTurn(1);
so I try to make the script do the setTurn() method in playerTurnObj() to save a 'turn' in a game I'm making. The problem is, it does not do the turn.setTurn(1); part because I keep getting the error above
what am I doing wrong? I searched, but I could not find an exact answer to my question.
This is not the way JavaScript works. Your "constructor" function contains inline functions that are not visible outside of the scope of playerTurnObj. So your variable turn does not have a method setTurn defined, as the error message states correctly. Probably you want something like this:
function playerTurnObj(set_turn) {
this.playerTurn=set_turn;
}
playerTurnObj.prototype = {
setTurn: function(turnToSet) {
this.playerTurn=turnToSet;
},
getTurn: function() {
return this.playerTurn;
}
};
Now your variable turn has two methods setTurn and getTurn that operate on the instance you created with new.
The setTurn and getTurn functions are private so they return undefined rather than invoking the function. You can do:
function playerTurnObj(set_turn) {
this.playerTurn=set_turn;
this.setTurn = setTurn;
this.getTurn = getTurn;
function setTurn(turnToSet) {
this.playerTurn=turnToSet;
}
function getTurn() {
return this.playerTurn;
}
}
You then have public setTurn and getTurn methods and can invoke them as follows:
var turn = new playerTurnObj();
turn.setTurn(1);
http://jsfiddle.net/Ht688/
What I make out of it is you need to return the object this in function playerTurnObj(). So your new code will look something like:
function playerTurnObj(set_turn) {
this.playerTurn=set_turn;
function setTurn(turnToSet) {
this.playerTurn=turnToSet;
}
function getTurn() {
return this.playerTurn;
}
return this;
}
bender: function () {
var context = {
pageName: 'Chocolatte candy'
},
partials = {
header: this.globalPartials.header,
tabbar: this.globalPartials.tabbar
};
addBackbuttonIphone();
$(this.el).html(templates["monkey"].render(context, partials));
return this;
}
});
return monkeyView;
});
in another location i have a js file that has the following function
function addBackbuttonIphone () {
context.backButton="#more";
}
If i just add context.backButton="more" in var context directly it works . However if i use the addBackButtonIphone function to do the same it does not work . I am sure that this function is being called however, it is not giving the "#more" value to context.backButton.
Please help
Thanks
modify your function signature to accept an argument called context, like this:
function addBackbuttonIphone(context) {
context.backButton="#more";
}
then pass context into your function, like this:
addBackbuttonIphone(context);
I'm using Class.js for creating classes.
I'm not getting the right context inside a method when invocked from a call back function
My code is
WordCloud = MyClass.extend({
init: function(data) {
var me = this;
(......).on("onComplete", this.draw);
},
show: function(word) {
alert(word)
},
draw : function(words){
console.debug(this); // prints element that triggred `onComplete` action
console.debug(words); // "Hi"
console.debug(me); // me is not defined
me.show(words) // Need to call this method
}
});
Problem is draw method is fired when an action is completed, but inside draw method this is not the actual class instance, but the element that triggred the callback action.
I can't pass exta arguments while calling this.draw as it is a call back function and onComplete has only one parameter.
How can I call the show method from draw?
If you do not have to support Internet Explorer 8 or lower, you can use bind():
init: function(data) {
var me = this;
(......).on("onComplete", this.draw.bind(this));
}
Otherwise, if you're already using jQuery, you can leverage $.proxy(), which works the same way:
init: function(data) {
var me = this;
(......).on("onComplete", $.proxy(this.draw, this));
}
I use a helper function for these cases.
function hitch(obj, func) {
return function() {
return obj[func].apply(obj, arguments || [])
};
}
To call it you would use hitch(this, 'draw'); instead of this.draw.
Or to make it even simpler you could add a simplified version to your base class
function hitch(func) {
var that = this;
return function() {
return that[func].apply(that, arguments || [])
};
}
And just call this.hitch('draw');.