Consider the below code:
$(".sceditor").sceditor({
emoticons: // contents from another file here
});
I want to load another file which contains a JSON
object as the value of the emoticons
option.
I tried the below:
$(".sceditor").sceditor({
emoticons: $.getJSON('../../images/emoticons/default/emoticons.json')
});
But that doesn't work because it returns
a JQXHR
object, not a JSON
object.
To get the value I believe I would need to do something like:
$(".sceditor").sceditor({
emoticons: $.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
// response is the JSON object
})
});
But obviously that is not going to work as the response
variable is inside the anonymous function and isn't returned to become the value of the emoticons
value.
I know I could wrap the whole sceditor
call inside the $.getJSON
call, but I don't really want the whole code to rely on a successful call to the emoticons file.
I then thought about doing this above it:
$.getJSON('../../images/emoticons/default/emoticons.json', function(response) {
var foo = response;
})
...but then how do I access foo
outside the scope?
What is generally the best way to do what I am trying to accomplish?
I would use the .done()
and .always()
promise methods on the jqxhr
object to accomplish this.
It sounds like what you want is to initialize the sceditor
regardless of whether you have emoticons or not. However, if you are able to load emoticons then you want to use those.
Here is a quick solution showing how to use the promise methods to achieve what you want. Obviously you can expand and make this better, but this can serve as a starting point.
// create a variable to store the results
var emoticons = false;
$.getJSON('../../images/emoticons/default/emoticons.json')
.done(function(result){
emoticons = result;
})
.always(function(){
// always initialize the sceditor
$('.my-selector').sceditor({emoticons: emoticons});
});
And the requisite jsFiddle: http://jsfiddle.net/oLspfLby/1/
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다