如果我创建一个大小为 [true, true] 的 famo.us 表面并将一些任意 html 内容放入其中,是否有一种干净的方法来检索对象的大小?
surface.getSize()
只是返回相同的[true,true]
我注意到有一些显然是私有的方法,例如:
s._currTarget.clientHeight
但使用这些似乎是在自找麻烦!
有几种方法可以解决这个问题。Famo.us 意识到了这个限制,它应该在优先级列表中非常高。
在此示例中,创建了一个新的表面类,该类在部署函数中或在渲染表面时发出事件。我肯定会在构建过程中获取对原始部署函数的引用,以便以后可以正常调用。收到渲染事件后,您可以根据需要编辑表面。
祝你好运!
var Engine = require('famous/core/Engine');
var Surface = require('famous/core/Surface');
var StateModifier = require('famous/modifiers/StateModifier');
var EventHandler = require('famous/core/EventHandler');
function MySurface(options) {
Surface.apply(this, arguments);
this._superDeploy = Surface.prototype.deploy;
}
MySurface.prototype = Object.create(Surface.prototype);
MySurface.prototype.constructor = MySurface;
MySurface.prototype.deploy = function deploy(target) {
this._superDeploy(target);
this.eventHandler.trigger('surface-has-rendered', this);
};
var context = Engine.createContext();
var event_handler = new EventHandler();
event_handler.on('surface-has-rendered', function(surface){
var size = surface.getSize();
var width = (size[0] == true) ? surface._currTarget.offsetWidth : size[0] ;
var height = (size[1] == true) ? surface._currTarget.offsetHeight : size[1] ;
surface.setSize([width,height]);
console.log(surface.getSize());
})
var surface = new MySurface({
size: [true,true],
content: "Hello",
properties: {
color: 'white',
textAlign: 'center',
padding: '20px',
backgroundColor: 'green'
}
})
surface.pipe(event_handler);
context.add(new StateModifier({origin:[0.5,0.5]})).add(surface);
传入当前true
返回..getSize
Surface
surface.getSize(true)
获得表面实际尺寸的最简单方法是surface.getSize(true)
. 您不需要继承 Surface。
但是,如果表面尚未渲染到 DOM,您将收到错误消息。当一个表面被渲染时,它会发出一个“部署”事件。你可以这样听:
surface.on('deploy', function () {
// Your Code Here
}.bind(this));
您很可能还必须将代码包装在 a 中Timer.setTimeout()
。这是因为该surface.getSize(true)
方法将比下一个渲染周期(每秒 60 帧或每个周期约 16 毫秒)执行得更快。最终代码将如下所示:
// With the rest of your require statements
var Timer = require('famous/utilities/Timer');
surface.on('deploy', function () {
Timer.setTimeout( function () {
// Your code here
// this.surface.getSize(true)
}.bind(this), 16);
}.bind(this));
我也是 Famo.us 的新手,但我不得不针对我的项目中的几种不同情况实施此修复,而且它似乎工作得很好。
请让我知道这对你有没有用。