Ember.js与Cloudkit JS

时间:2016-02-03 22:30:45

标签: javascript ember.js cloudkit

我已经使用CloudKit JS构建了一个小型原型项目,现在我开始构建它的下一个版本,并且我想使用Ember,因为我有一些基本的经验。但是,我不太确定在哪里放置CloudKit JS代码。例如,我应该在哪里添加配置部分和auth功能?我想,一旦找到了auth代码的位置,我就可以将一些查询函数添加到各个视图和组件中,对吗?

这是我的配置代码(删除了容器和ID):

CloudKit.configure({
containers: [{

  containerIdentifier: '###',

  // @todo Must generate a production token for app store version
  apiToken: '###',

  auth: {
    persist: true
  },

  // @todo Must switch to production for app store version
  environment: 'development'
}]
});

这是auth功能:

function setupAuth() {

  // Get the container.
  var container = CloudKit.getDefaultContainer();

  //Function to call when user logs in
  function gotoAuthenticatedState( userInfo ) {

    // Checks if user allows us to look up name
    var userName = '';
    if ( userInfo.isDiscoverable ) {
      userName = userInfo.firstName + ' ' + userInfo.lastName;
    } else {
      userName = 'User record name: ' + userInfo.userRecordName;
    }

    //Calls out initialization function
    init();

    //Sets up UI for logged in users
    setAuthenticatedUI( userName );

    //Register logged out function
     container
      .whenUserSignsOut()
      .then( gotoUnauthenticatedState );
  }

  //Function to call when user logs out
  function gotoUnauthenticatedState( error ) {

    //Checks if error occurred
    if ( error && error.ckErrorCode === 'AUTH_PERSIST_ERROR' ) {
      displayError( logOutError, 'Error code: AUTH_PERSIST_ERROR' );
    }

    // Sets up the UI for logged out users
    setUnauthenticatedUI();

    //Register logged in function
    container
      .whenUserSignsIn()
      .then( gotoAuthenticatedState )
      .catch( gotoUnauthenticatedState );
  }

  // Check a user is signed in and render the appropriate button.
  return container.setUpAuth()
    .then( function( userInfo ) {

      // userInfo is the signed-in user or null.
      if ( userInfo ) {
        gotoAuthenticatedState( userInfo );
      } else {
        gotoUnauthenticatedState();
      }
    });
}

init()然后调用函数来设置查询,以使用记录将图表添加到页面。 setAuthenticatedUI()和setUnauthenticatedUI()函数只需在用户通过身份验证后应用和删除类。

1 个答案:

答案 0 :(得分:0)

答案很大程度上取决于您使用的Ember版本以及您计划如何使用它。有路线?简单的路线? RouteHandlers?

例如,如果你在Ember v2.3.0,你可以考虑使用依赖注入(https://guides.emberjs.com/v2.3.0/applications/dependency-injection/)来为你的应用程序的其余部分提供一个已配置的容器实例,例如:

export function initialize(application) {
  var container = CloudKit.configure(config).getDefaultContainer();

  application.register('ckcontainer:main', container);
  application.inject('route', 'ckcontainer', 'ckcontainer:main');
}

export default {
  name: 'ckcontainer',
  initialize: initialize
};

然后在一个路线中,您可以获得这样的参考:

export default Ember.Route.extend({
  activate() {
    // The ckcontainer property is injected into all routes
    var db = this.get('ckcontainer').privateCloudDatabase;
  }
});

-HTH