开发者

Dojo scope question for store.query with ItemFileWriteStore

I am writing a method to grab the lowest unique id in an ItemFileWriteStore. I have a boolean to tell me when I reach my condition, but I can't get the scope correct.

The function call works as I expect, apart from when newIdOkay is set to true, it is not recognised in the while loop.

Please can you explain why and what I have to do to get this right?

Many thanks

Here is my code:

function checkNewId( size ) {
    if( size == 0 ) {
        console.log('found new ID!');
        newIdOkay = true;
    }
 }

function addContentItem( store ) {    
    // New ID 
    var newIdOkay = false;
    var newId = 0;

    while( newIdOkay == false &&开发者_如何学Camp; newId < 8 ) {
        newId++;
        store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),                          
                      start:0, count:0, sync:true });
    }
} 


To understand the reason, you need to have basic understanding of identifier resolution and scope chain in JavaScript. I recommend you to read this article: http://jibbering.com/faq/notes/closures/

Regarding you question, in the function addContentItem, the check in the while loop is tested against the identifier newIdOkay which is in the of the activation object corresponding to this function execution context. In the function checkNewId, the identifier newIdOkay you set is in the global object. So these two are not the same one. An easy fix is to move the newIdOkay in addContentItem function to the global scope.

var newIdOkay = false;

function checkNewId( size ) {
    if( size == 0 ) {
        console.log('found new ID!');
        newIdOkay = true;
    }
 }

function addContentItem( store ) {    
    // New ID 

    var newId = 0;

    while( newIdOkay == false && newId < 8 ) {
        newId++;
        store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),                          
                  start:0, count:0, sync:true });
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜