我现在经常使用Sails,我有一个练习题。现在,当我想在项目中反复使用NPM包时,我在config/bootstrap.js
文件中添加了这样的内容:
module.exports.bootstrap = function(cb) {
sails.Q = require('q');
sails.url = require('url');
...
cb();
};
我这样做是为了在任何控制器中使用像Q这样的包,而不必多次require('q')
。我只需要sails.Q.[...]
。有没有更好的方法来实现同样的目标?我希望能够通过Q.[...]
而不是sails.Q.[...]
来引用该包。有谁知道更好的方法吗?
答案 0 :(得分:0)
如果只是为了保存击键,你真的应该添加
import tkinter as tk
import numpy as np
from PIL import Image, ImageTk
# drag callbacks
dragged_item = None
current_coords = 0, 0
def start_drag(event):
global current_coords
global dragged_item
result = canvas.find_withtag('current')
if result:
dragged_item = result[0]
current_coords = canvas.canvasx(event.x), canvas.canvasy(event.y)
else:
dragged_item = None
def stop_drag(event):
dragged_item = None
def drag(event):
global current_coords
xc, yc = canvas.canvasx(event.x), canvas.canvasy(event.y)
dx, dy = xc - current_coords[0], yc - current_coords[1]
current_coords = xc, yc
canvas.move(dragged_item, dx, dy)
#Create pictures
blue_square_transparent_border = [[[0,0,0,0]]*100]*10 + [[[0,0,0,0]]*30 + [[0,0,255,255]]*40 + [[0,0,0,0]]*30]*40 + [[[0,0,0,0]]*100]*10
blue_square_transparent_border = np.array(blue_square_transparent_border, dtype='uint8')
pil_image = Image.fromarray(blue_square_transparent_border)
background_data = np.zeros((200, 400, 4))
background_data[:, :, 0] = 255 * np.ones((200, 400))
background_data[:, :, 3] = 255 * np.ones((200, 400))
background_data = np.array(background_data, dtype='uint8')
pil_image_bg = Image.fromarray(background_data)
# create GUI
root = tk.Tk()
background_image = ImageTk.PhotoImage(pil_image_bg)
tk_image = ImageTk.PhotoImage(pil_image)
canvas = tk.Canvas(root, width=400, height=200)
canvas.pack()
# bind 'draggable' tag to mouse events
canvas.tag_bind('draggable', '<ButtonPress-1>', start_drag)
canvas.tag_bind('draggable', '<ButtonRelease-1>', stop_drag)
canvas.tag_bind('draggable', '<B1-Motion>', drag)
# display pictures
canvas.create_image(0, 0, image=background_image, anchor='nw')
canvas.create_image(0, 0, image=tk_image, anchor='nw', tag='draggable')
root.mainloop()
在您使用它的每个文件的顶部。var Q = require('q')
每次都不会重新评估模块。在第一次调用之后,调用它只是从缓存中获取模块的导出,因此每个文件使用它就没有任何开销。
但是,如果你承认这是不好的做法而且你没关系,你可以像这样全局导出:
require()
这样您就可以从任何文件中引用global.Q = require('q')
。
答案 1 :(得分:-1)
您可以在启动服务器之前在 app.js 中执行var Q = require('q');
(即sails.lift(rc('sails'));
)。