简体   繁体   English

在流星项目中插入javascript代码:最佳做法

[英]inserting javascript code in a meteor project: best practice

I have a meteor project, and I have a client folder (seen only by the client), a server folder (seen only by the server) and a lib folder (seen by both client and server). 我有一个流星项目,并且有一个client文件夹(仅由客户端可见), server文件夹(仅由服务器可见)和lib文件夹(由客户端和服务器均可见)。

I have in /client/devices two files, devices.html and devices.js , that are parts of an HTML page. 我在/client/devices两个文件devices.htmldevices.js ,它们是HTML页面的一部分。

I have to insert in this page this date picker: however, the instructions says that I have to insert at bottom of the page (so it can be loaded after the page is completely loaded) this line: 我必须在此页面中插入日期选择器:但是,说明说我必须在页面底部插入(以便可以在页面完全加载后加载)此行:

var picker = new Pikaday({ field: document.getElementById('datepicker') });

I tried to put it directly after the tag, in a tag; 我试图将其直接放在标签后的标签中; and it works: 它的工作原理是:

<input type="text" id="datepicker">
<script>
    var picker = new Pikaday({ field: document.getElementById('datepicker') });
</script>

I tried also to put it in Template.devices.onRendered but it does not work. 我也尝试将其放在Template.devices.onRendered但它不起作用。

my question is: since I'm not sure if it is a good practice to put code in the middle of an html file, where should I put this part? 我的问题是:由于我不确定将代码放在html文件的中间是否是一个好习惯,因此我应该将这部分放在哪里?

There's a few things you need to do to ensure that 3rd party code will work in a Meteor app. 您需要做一些事情来确保第三方代码在Meteor应用程序中可以正常工作。

  1. Ensure you've installed the package either through Atmosphere or npm . 确保已通过Atmosphere或npm安装了该软件包。
  2. Import the package in the file you want to use it. 将包导入到要使用的文件中。
  3. Initialize the code when the UI is ready. UI就绪后,初始化代码。

For example: 例如:

client/main.html client / main.html

<body>
  {{> devices}}
</body>

<template name="devices">
  <input type="text" id="datepicker">
</template>

client/main.js 客户端/ main.js

import { Template } from 'meteor/templating';
import Pikaday from 'pikaday';

import './main.html';

Template.devices.onRendered(function devicesOnRendered() {
  new Pikaday({ field: document.getElementById('datepicker') });
});

package.json package.json

{
  "name": "test",
  "private": true,
  "scripts": {
    "start": "meteor run"
  },
  "dependencies": {
    "babel-runtime": "^6.20.0",
    "meteor-node-stubs": "~0.2.4",
    "pikaday": "latest"
  }
}

Meteor Guide on Packaging 包装流星指南

https://guide.meteor.com/atmosphere-vs-npm.html https://guide.meteor.com/structure.html#importing-from-packages https://guide.meteor.com/atmosphere-vs-npm.html https://guide.meteor.com/structure.html#importing-from-packages

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM