1

I'm building an offline HTML page using Angular and using ydn-db for offline storage.

I have a database service like so,

demoApp.SericeFactory.database  = function database() {
    var database = {
        dataStore: null,
        admins: [],
        students: [],
        errors: [],
        getadmindata: function(username) {
           self = null, that = this 
           database.dataStore.get('admins', username).done(function(record) {
                that.self = record;
                return record;
           }).fail(function(e) {
                console.log(e);
                database.errors.push(e);
           });
           return self; //This does not change.
        }
     };

   database.dataStore = new ydn.db.Storage('DemoApp');

   angular.forEach(INITSTUDENTS, function(student) {
       database.dataStore.put('students', student, student.matricno);
    database.students.push(student);
   });

   angular.forEach(INITADMINS, function(admin) {
   database.dataStore.put('admins', admin, admin.username);
    database.admins.push(admin);
   });

   return database;

I also have a controller that attempts to use the database;

function AppCntl ($scope, database) {
     var user = database.getadmindata('user'); //I get nothing here.
}

What I have tried, I have tried making changing self to var self I have tried splitting the function like so

rq = database.dataStore.get('admins', 'user');
rq.done(function(record), {
   self = record;
   alert(self.name) //Works.
});
   alert(self) //Doesn't work.

I have gone through questions like this o StackOverflow but nothings seems to be working for me or maybe I have just been looking in the wrong place.

4

1 回答 1

0

数据库请求是异步的,因此它会在代码执行结束后稍后执行。

所以当最后一次alert执行时,self 仍然是未定义的。在数据库请求完成后alert执行第二次,这是通常的正确设计模式。

编辑:

我使用以下代码取得了成功:

// Database service
angular.module('myApp.services', [])
  .factory('database', function() {
    return new ydn.db.Storage('feature-matrix', schema);
  }
});

// controller using database service
angular.module('myApp.controllers', [])
 .controller('HomeCtrl', ['$scope', 'utils', 'database', function($scope, utils, db) {
  var index_name = 'platform, browser';
  var key_range = null;
  var limit = 200;
  var offset = 0;
  var reverse = false;
  var unique = true;
  db.keys('ydn-db-meta', index_name, key_range, limit, offset, reverse, unique)
      .then(function(keys) {
        var req = db.values('ydn-db', keys);
        req.then(function(json) {
          $scope.results = utils.processResult(json);
          $scope.$apply();
        }, function(e) {
          throw e;
        }, this);
      });
}])

完整的应用程序可在https://github.com/yathit/feature-matrix

运行演示应用程序在这里:http ://dev.yathit.com/demo/feature-matrix/index.html

于 2013-10-04T10:23:16.937 回答